package com.aries.ui.view.alpha;

import com.aries.ui.view.alpha.delegate.AlphaDelegate;
import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import ohos.agp.utils.Rect;
import ohos.app.Context;
import ohos.hiviewdfx.HiLog;
import ohos.multimodalinput.event.TouchEvent;

/**
 * @Author: AriesHoo on 2018/7/19 9:56
 * @E-Mail: AriesHoo@126.com
 * Function: 控制Alpha 按下效果
 * Description:
 */
public class AlphaTextView extends Text implements Component.TouchEventListener {

    private AlphaDelegate delegate;

    public AlphaTextView(Context context) {
        this(context, null);
    }

    public AlphaTextView(Context context, AttrSet attrs) {
        this(context, attrs, "");
    }

    public AlphaTextView(Context context, AttrSet attrs, String styleName) {
        super(context, attrs, styleName);
        delegate = new AlphaDelegate(this);
        setTouchEventListener(this);
    }

    public AlphaDelegate getDelegate() {
        return delegate;
    }

    @Override
    public void setPressState(boolean pressState) {
        super.setPressState(pressState);
        delegate.getAlphaViewHelper().onPressedChanged(this, pressState);
    }

    @Override
    public void setEnabled(boolean enabled) {
        super.setEnabled(enabled);
        delegate.getAlphaViewHelper().onEnabledChanged(this, enabled);
    }


    @Override
    public boolean onTouchEvent(Component component, TouchEvent touchEvent) {
        if (!isEnabled()) {
            return true;
        }
        int action = touchEvent.getAction();
        switch (action) {
            case TouchEvent.PRIMARY_POINT_DOWN:
                setPressState(true);
                break;
            case TouchEvent.PRIMARY_POINT_UP:
                setPressState(false);
                break;
            case TouchEvent.POINT_MOVE:
                int index = touchEvent.getIndex();
                int x = (int) touchEvent.getPointerScreenPosition(index).getX();
                int y = (int) touchEvent.getPointerScreenPosition(index).getY();
                if (isOutsideView(x, y)) {
                    setPressState(false);
                }
                break;
            case TouchEvent.CANCEL:
                setPressState(false);
                break;
        }

        return true;
    }

    /**
     * touch是否移出view之外
     * @param x x
     * @param y Y
     * @return touch是否移出view之外
     */
    private boolean isOutsideView(int x, int y) {
        int[] location = getLocationOnScreen();
        int pointx = x - location[0];
        int pointy = y - location[1];
        boolean flag = false;
        Rect rect = new Rect();
        getSelfVisibleRect(rect);
        if (!rect.isInclude(pointx, pointy)) {
            flag = true;
        }
        return flag;
    }

}
